package com.haiyou.crawler.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.CookieStore;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.InputStream;

/**
 * @author chenzeke
 * @date 2019/9/5 13:10
 */
@Slf4j
public class HttpUtil {

    public static String imageContentType = "image/jpg";
    private static CookieStore cookieStore = new BasicCookieStore();

    public static DefaultHttpClient getBuilder() {
        DefaultHttpClient httpclient = new DefaultHttpClient();
        httpclient.setCookieStore(cookieStore);
        return httpclient;
    }

    /**
     * 获取图片验证码
     *
     * @param url
     * @return
     * @throws Exception
     */
    public static String doGetImage(String url) throws Exception {
        HttpGet request = new HttpGet(url);
        CloseableHttpResponse response = getBuilder().execute(request);
        response.setHeader("content-type", imageContentType);
        HttpEntity entity = response.getEntity();
        InputStream inputStream = entity.getContent();
        String result = ImageUtil.getImageCode(inputStream);
        log.info("图片识别===>" + result);
        return result;
    }

}
